//
// Created by Criinal Nicole on 2020/6/15.
//

#include "User.h"
#include <cstring>

// 判断用户是否合法
bool USER::User::isValid() {
    return _userId <= MAX_USER_NUM && _privilege > 0;
}

// 判断密码是否正确
// 匹配则返回true
bool USER::User::checkPassword(char *password) {
    return !strcmp(password, _password);
}

// 设置密码
// 长度超过上限则返回false
bool USER::User::setPassword(char *password) {
    if (strlen(password) >= PASSWORD_SIZE) return false;
    strcpy(_password, password);
    return true;
}

// 判断用户名是否匹配
// 匹配则返回true
bool USER::User::checkName(char *name) {
    return !strcmp(_name, name);
}

// 设置用户名
// 长度超过上限则返回false
bool USER::User::setName(char *name) {
    if (strlen(name) >= USER_NAME_SIZE)return false;
    strcpy(_name, name);
    return true;
}

USER::User *USER::Admin;

int USER::currentUserNumber;

USER::User USER::Users[MAX_USER_NUM];

// 初始化用户
void USER::init() {
    Admin = Users;
    Admin->_userId = 0;
    Admin->_privilege = 1;
    Admin->setName((char *) "admin");
    Admin->setPassword((char *) "20174436");
    currentUserNumber = 1;
    for (int i = 1; i < MAX_USER_NUM; ++i) {
        Users[i] = {};
    }
}

//非格式化加载
void USER::load() {
    currentUserNumber = 0;
    Admin = Users;
    while (Users[currentUserNumber]._privilege > 0)currentUserNumber++;
}

int USER::addUser(USER::User user) {
    if (currentUserNumber >= MAX_USER_NUM)return -1;
    user._userId = currentUserNumber;
    Users[currentUserNumber++] = user;
    return 0;
}

USER::User USER::findUser(char *name) {
    for (int i = 0; i < currentUserNumber; ++i) {
        if (Users[i].checkName(name))return Users[i];
    }
    return {};
}







